﻿/**************************************************************************************************************
 * Class name:  StreamHelper.cs
 * Description: 流操作助手
 * Author:      Ju2ender
 * Create:      2012-10-11 Thursday 10:41:34
 * Update:      2012-10-11 Thursday 10:41:34
 **************************************************************************************************************/

using System;
using System.IO;
using System.Text;

namespace DearLee.Toolkit.IO {

  /// <summary>
  /// 流操作助手
  /// </summary>
  public class StreamHelper {

    /// <summary>
    /// 写入数据
    /// </summary>
    /// <param name="path">路径及文件名</param>
    /// <param name="append">ture：追加，false：覆盖</param>
    /// <param name="encoding">要使用的字符编码</param>
    /// <param name="data">要写入的数据</param>
    public static void WriteData(string path, bool append, Encoding encoding, string data) {

      StreamWriter writer = null;
      string directoryName = string.Empty;

      directoryName = Path.GetDirectoryName(path);

      // 若路径不存在则创建
      if (!Directory.Exists(directoryName)) {
        Directory.CreateDirectory(directoryName);
      }

      writer = new StreamWriter(path, append, encoding);
      writer.Write(data);
      writer.Flush();
      writer.Close();
      writer.Dispose();
    }

    /// <summary>
    /// 读取数据
    /// </summary>
    /// <param name="path">路径及文件名</param>
    /// <returns>文件中的数据</returns>
    public static string ReadData(string path) {

      StreamReader reader = null;
      string sLine, sContext;

      // 若文件不存在则返回空
      if (!File.Exists(path)) {
        return null;
      }

      sLine = sContext = string.Empty;
      reader = new StreamReader(path);

      while (sLine != null) {
        sLine = reader.ReadLine();

        if (sLine != null) {
          sContext += sLine + Environment.NewLine;
        } else {
          break;
        }
      }

      reader.Close();
      reader.Dispose();

      return sContext.Trim();
    }
  }
}
